package com.adpython.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @author wenhua.yang
 * @date 2009-7-8
 */
public class StrUtil {
	
	final static char[] digits = {
    	'0' , '1' , '2' , '3' , '4' , '5' ,
    	'6' , '7' , '8' , '9' , 'A' , 'B' ,
    	'C' , 'D' , 'E' , 'F' , 'G' , 'H' ,
    	'I' , 'J' , 'K' , 'L' , 'M' , 'N' ,
    	'O' , 'P' , 'Q' , 'R' , 'S' , 'T' ,
    	'U' , 'V' , 'W' , 'X' , 'Y' , 'Z'
    };
	
	public static boolean empty(String str){
		if((str==null) || str.trim().equals(""))
			return true;
		return false;
	}
	
	public static String md5(byte[] bytes){
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(bytes);
			byte[] theDigest = md5.digest();
			if (theDigest == null)
				return null;
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < theDigest.length; i++) {
				sb.append(toUnsignedString(theDigest[i] & 0x00FF, 4, 2));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
		
	private static String toUnsignedString(int i, int shift, int width) {
		char[] buf = new char[8];
		Arrays.fill(buf, digits[0]);
		int charPos = 8;
		int radix = 1 << shift;
		int mask = radix - 1;
		do {
			buf[--charPos] = digits[i & mask];
			i >>>= shift;
		} while (i != 0);

		return new String(buf, Math.min(charPos, 8 - width), Math.max(8 - charPos, width));
	}
}
